package lupita.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lupita.model.vos.RecomendationsCI;

import lupita.model.vos.FileSystemItem;
import lupita.persistence.MySQLImpl;

/**
 * Servlet implementation class RecomendationSvt
 */
public class RecomendationSvt extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MySQLImpl mysql;
	private MySQLImpl mysql2;
	
	HashMap<String,HashMap> dictionary=new HashMap<String, HashMap>();
	HashMap<String, Double> data;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RecomendationSvt() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//obtener el id usuario de la sesion
		HttpSession session = request.getSession();		
		int userID = (Integer)session.getAttribute("IdUser");
		String usernameSession = "";
		
		ResultSet resultUsers;
		ResultSet result;
		
		try {
			mysql = new MySQLImpl();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String queryUser = "Select id, username from user";
		
		try{
			
			String username = "" ;
			String filename;
			Double rate;
			
			ArrayList<Integer> users = new ArrayList<Integer>();
			mysql.openConnection();
			
			resultUsers=  mysql.selectSQL(queryUser);
			
			resultUsers.beforeFirst();
			
			
			while(resultUsers.next()){
				int idUser = resultUsers.getInt("id");
				users.add(idUser);	
				if(idUser == userID){
					usernameSession = resultUsers.getString("username");
				}
				
			}															
			for(int id: users){
				String query = "select u.username, f.name, r.rate" +
				" from file as f, fileRating fr, user as u, rating as r" +
				" where f.id = fr.idFile" +
				" and u.id = fr.idUser" +
				" and r.id = fr.idRating"+
				" and fr.idUser = " + id;
				
				result = mysql.selectSQL(query);
				result.beforeFirst();
				data = new HashMap<String, Double>();
				while(result.next()){
					
					username = result.getString("username");
					filename = result.getString("name");
					rate = result.getDouble("rate");							
				
					System.out.println("Username: "+username+" Filename: " + filename + " Rate: "+ rate);
				    
					data.put(filename, rate);
    			}
				if(!data.isEmpty()){
					dictionary.put(username, data);
				}								
				
			}
			
			
			if(!dictionary.isEmpty()){
				PrintWriter out = response.getWriter();
				/*
				SortedMap<Double, String> recomendatiosPearson = RecomendationsCI.getRecomendations(dictionary, usernameSession,1);
		        System.out.println(" ");
		        System.out.println(" ");
		        System.out.println("--------Recomendations Pearson----------------");
		        System.out.println(" ");
		        */
		        SortedMap<Double, String> recomendatiosPearson = RecomendationsCI.getRecomendations(dictionary, usernameSession,1);
		        
		        String strResponse = "<table border='1' align='center'>";
		        strResponse += "<tr><td colspan='2'><div style='background-color: #0099CC;font-size:16px; font-weight:bold;color:#FFFFFF;'>&nbsp;&nbsp;Recomendaciones</div></td></tr>";
		        strResponse += "<tr><th>File</th><th>Rating</th></tr>";
		        
		        Map.Entry datosPearson;        
		        for (Iterator iterator = recomendatiosPearson.entrySet().iterator(); iterator.hasNext();) {
		        	datosPearson  = (Map.Entry) iterator.next();        	
		        	System.out.println("File: " + datosPearson.getValue() + " rating: [" + datosPearson.getKey() +"]<br/>" );	
		        	
		        	strResponse += "<tr><td>" + datosPearson.getValue() + "</td> <td>: [" + datosPearson.getKey() +"]</td></tr>" ;
				}
		        strResponse += "</table>";
		        out.print(strResponse);
			}
				mysql.closeConnection();			
								
		}catch(Exception e){
			e.printStackTrace();
		}	
		
										
		//pasar el hashMap a la funcion de recomendation.
		
		//imprimir resultados.
	}
	
	
}
